#include "timer.h"

void TimerInit(void)	        // Initialize our timer (Get it ready)
{
	memset(&timer, 0, sizeof(timer));		// Clear our timer structure

	// Check to see if a performance counter is available
	// If one is available the timer frequency will be updated
	if (!QueryPerformanceFrequency((LARGE_INTEGER *) &timer.frequency))
	{
		// No Performace Counter Available
		timer.performance_timer	= false;        	// Set performance timer to FALSE
		timer.mm_timer_start = timeGetTime();           // Use timeGetTime() to get current time
		timer.resolution = 1.0f/1000.0f;                // Set our timer resolution to .001f
		timer.frequency	= 1000;		        	// Set our timer frequency to 1000
		timer.mm_timer_elapsed = timer.mm_timer_start;  // Set the elapsed time to the current time
	}
	else
	{
		// Performance counter is available, use it instead of the multimedia timer
		// Get the current time and store it in performance_timer_start
		QueryPerformanceCounter((LARGE_INTEGER *) &timer.performance_timer_start);
		timer.performance_timer = true;                 // Set performance timer to TRUE
		// Calculate the timer resolution using the timer frequency
		timer.resolution = (float) (((double)1.0f)/((double)timer.frequency));
		// Set the elapsed time to the current time
		timer.performance_timer_elapsed	= timer.performance_timer_start;
	}
}

float TimerGetTime()            // Get time in milliseconds
{
	__int64 time;		// time will hold a 64 bit integer

	if (timer.performance_timer)    // Are we using the performance timer?
	{
		QueryPerformanceCounter((LARGE_INTEGER *) &time);	// Grab the current performance time
		// Return the current time minus the start time multiplied by the resolution and 1000 (To get MS)
		return ( (float) ( time - timer.performance_timer_start) * timer.resolution)*1000.0f;
	}
	else
	{
		// Return the current time minus the start time multiplied by the resolution and 1000 (To get MS)
		return( (float) ( timeGetTime() - timer.mm_timer_start) * timer.resolution)*1000.0f;
	}
}

void TimerReset(void)	        // Reset our timer (Get it ready)
{
        if (timer.performance_timer == true) {
           QueryPerformanceCounter((LARGE_INTEGER *) &timer.performance_timer_start);
           timer.performance_timer_elapsed	= timer.performance_timer_start;
        }
        else
        {
           timer.mm_timer_start = timeGetTime();           // Use timeGetTime() to get current time
           timer.mm_timer_elapsed = timer.mm_timer_start;  // Set the elapsed time to the current time
        }
}